'use client'

import React from 'react';
import { ComponentConfig, ComponentListRenderer } from './ComponentRenderer';

interface PageRendererProps {
  components: ComponentConfig[];
  loading?: boolean;
  error?: string | null;
  onRetry?: () => void;
  className?: string;
  itemClassName?: string;
  loadingComponent?: React.ReactNode;
  errorComponent?: (error: string, retry: () => void) => React.ReactNode;
  emptyComponent?: React.ReactNode;
}

export default function PageRenderer({ 
  components,
  loading = false,
  error = null,
  onRetry,
  className, 
  itemClassName,
  loadingComponent,
  errorComponent,
  emptyComponent
}: PageRendererProps) {

  // 默认加载组件
  const defaultLoadingComponent = (
    <div className="min-h-screen flex items-center justify-center">
      <div className="text-center">
        <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-[#f7b401] mx-auto mb-4"></div>
      </div>
    </div>
  );

  // 默认错误组件
  const defaultErrorComponent = (error: string, retry: () => void) => (
    <div className="min-h-screen flex items-center justify-center">
      <div className="text-center">
        <div className="text-red-500 text-6xl mb-4">⚠️</div>
        <h2 className="text-xl font-semibold text-gray-700 mb-2">加载失败</h2>
        <p className="text-gray-500 mb-4">{error}</p>
        <button 
          onClick={retry}
          className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
        >
          重试
        </button>
      </div>
    </div>
  );

  // 默认空内容组件
  const defaultEmptyComponent = (
    <div className="min-h-screen flex items-center justify-center">
      <div className="text-center">
        <div className="text-gray-400 text-6xl mb-4">📝</div>
        <h2 className="text-xl font-semibold text-gray-700 mb-2">页面为空</h2>
        <p className="text-gray-500">页面暂无内容，请在管理后台添加组件</p>
      </div>
    </div>
  );

  // 加载状态
  if (loading) {
    return loadingComponent || defaultLoadingComponent;
  }

  // 错误状态
  if (error) {
    const handleRetry = onRetry || (() => {});
    return errorComponent ? errorComponent(error, handleRetry) : defaultErrorComponent(error, handleRetry);
  }

  // 无组件状态
  if (components.length === 0) {
    return emptyComponent || defaultEmptyComponent;
  }

  // 渲染页面内容
  return (
    <ComponentListRenderer 
      components={components} 
      className={className}
      itemClassName={itemClassName}
    />
  );
}
